﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Sirius.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Web;

namespace Sirius.SiriusAPI
{
    public static class SiriusHttpServer
    {
        //创建用于监听WEB域的对象
        static HttpListener httpServer = new HttpListener();
        //创建用于http请求的token
        static string httpToken;

        /// <summary>
        /// httpServer初始化
        /// </summary>
        public static void httpServerInit()
        {
            //获取用于http请求的token
            httpToken = JsonDocument.Parse(new StreamReader("Config.json").ReadToEnd()).RootElement.GetProperty("token").GetString();
            //读取配置文件获取HttpServer监听端口，并添加监听域
            httpServer.Prefixes.Add("http://+:" + JsonDocument.Parse(new StreamReader("Config.json").ReadToEnd()).RootElement.GetProperty("httpPort").GetString() + "/");
            //启动HttpServer
            try
            {
                httpServer.Start();
            }
            catch (Exception ex)
            {
                Log.Log.LogWar("HttpApi", "HttpAPI未成功启动，端口可能被占用或未使用管理员权限运行" + ex.Message);
            }


        }

        /// <summary>
        /// 循环接受请求
        /// </summary>
        public static void httpAccept()
        {
            Task.Run(async () =>
            {
                while (true)
                {
                    //获取客户端对象
                    HttpListenerContext Client = httpServer.GetContext();
                    //获取客户端的请求对象
                    HttpListenerRequest request = Client.Request;
                    //获取客户端的响应对象 
                    HttpListenerResponse response = Client.Response;

                    //设置响应编码
                    response.ContentType = "application/json;charset=UTF-8";
                    //获取响应内容流对象
                    Stream outStream = response.OutputStream;
                    //获取读取参数流对象
                    var InputStream = request.InputStream;
                    StreamReader InputReader = new StreamReader(InputStream, Encoding.UTF8);

                    //获取请求参数对象
                    var param = request.QueryString;
                    //获取请求模式
                    var httpMethod = request.HttpMethod;
                    //判断token是否正确，错误返回
                    if(httpMethod.Equals("GET") || httpMethod.Equals("POST"))
                    {
                        byte[] buffer;
                        if (param.Get("token") == httpToken)
                        {
                            string action = param.Get("action");
                            switch (action)
                            {
                                case "sendMessage"://发送消息
                                    string channel_id = param.Get("channel_id");
                                    string msg = param.Get("msg");
                                    string embedMsg = param.Get("embed");
                                    string arkMsg = param.Get("ark");
                                    string referenceMsg = param.Get("reference");
                                    string image = param.Get("image");
                                    string msg_id = param.Get("msg_id");
                                    string event_id = param.Get("event_id");
                                    string markdownMsg = param.Get("markdown");
                                    buffer = Encoding.UTF8.GetBytes(OpenAPI.openAPI.sendMessage(channel_id, msg, embedMsg, arkMsg, referenceMsg, image, msg_id, event_id, markdownMsg));
                                    outStream.Write(buffer, 0, buffer.Length);
                                    outStream.Close();
                                    break;
                                case "getBotInfo"://获取机器人信息
                                    buffer = Encoding.UTF8.GetBytes(OpenAPI.openAPI.getBotInfo());
                                    outStream.Write(buffer, 0, buffer.Length);
                                    outStream.Close();
                                    break;
                                case "getGuildList"://获取频道列表
                                    string before = param.Get("before");
                                    string after = param.Get("after");
                                    string limit = param.Get("limit");
                                    buffer = Encoding.UTF8.GetBytes(OpenAPI.openAPI.getGuildList(before, after, limit));
                                    outStream.WriteAsync(buffer, 0, buffer.Length);
                                    outStream.Close();
                                    break;
                                case "getGuildInfo"://获取频道详情
                                    string guild_id = param.Get("guild_id");
                                    buffer = Encoding.UTF8.GetBytes(OpenAPI.openAPI.getGuildInfo(guild_id));
                                    outStream.WriteAsync(buffer, 0, buffer.Length);
                                    outStream.Close();
                                    break;
                                case "getChannelList"://获取子频道列表
                                    guild_id = param.Get("guild_id");
                                    buffer = Encoding.UTF8.GetBytes(OpenAPI.openAPI.getChannelList(guild_id));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "createChannel"://创建子频道
                                    guild_id = param.Get("guild_id");
                                    string name = param.Get("name");
                                    string type = param.Get("type");
                                    string sub_type = param.Get("sub_type");
                                    string position = param.Get("position");
                                    string parent_id = param["parent"];
                                    string private_type = param.Get("private_type");
                                    string private_user_ids = param.Get("private_user_ids");
                                    string speak_permission = param.Get("speak_permission");
                                    string application_id = param.Get("application_id");
                                    buffer = Encoding.UTF8.GetBytes(OpenAPI.openAPI.createChannel(guild_id, name, type, sub_type, position, parent_id, private_type, private_user_ids, speak_permission, application_id));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "setChannelInfo"://修改子频道
                                    channel_id = param.Get("channel_id");
                                    name = param.Get("name");
                                    position = param.Get("position");
                                    parent_id = param["parent"];
                                    private_type = param.Get("private_type");
                                    speak_permission = param.Get("speak_permission");
                                    buffer = Encoding.UTF8.GetBytes(OpenAPI.openAPI.setChannelInfo(channel_id, name, position, parent_id, private_type, speak_permission));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "deleteChannel"://删除子频道
                                    channel_id = param.Get("channel_id");
                                    buffer = Encoding.UTF8.GetBytes(Convert.ToString(OpenAPI.openAPI.deleteChannel(channel_id)));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "getGuildRoleList"://获取频道身份组列表
                                    guild_id = param.Get("guild_id");
                                    buffer = Encoding.UTF8.GetBytes(OpenAPI.openAPI.getGuildRoleList(guild_id));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "createGuildRole"://创建频道身份组
                                    guild_id = param.Get("guild_id");
                                    name = param.Get("name");
                                    String color = param.Get("color");
                                    string hoist = param.Get("hoist");
                                    buffer = Encoding.UTF8.GetBytes(OpenAPI.openAPI.createGuildRole(guild_id, name, color, hoist));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "getChannelInfo"://获取子频道详情
                                    channel_id = param.Get("channel_id");
                                    buffer = Encoding.UTF8.GetBytes(OpenAPI.openAPI.getChannelInfo(channel_id));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "setGuildRole"://修改频道身份组
                                    guild_id = param.Get("guild_id");
                                    color = param.Get("color");
                                    name = param.Get("name");
                                    hoist = param.Get("hoist");
                                    string role_id = param.Get("role_id");
                                    buffer = Encoding.UTF8.GetBytes(OpenAPI.openAPI.setGuildRole(guild_id, role_id, name, color, hoist));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "deleteGuildRole"://删除频道身份组
                                    guild_id = param.Get("guild_id");
                                    role_id = param.Get("role_id");
                                    buffer = Encoding.UTF8.GetBytes(Convert.ToString(OpenAPI.openAPI.deleteGuildRole(guild_id, role_id)));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "addRoleMember"://添加身份组成员
                                    guild_id = param.Get("guild_id");
                                    role_id = param.Get("role_id");
                                    string user_id = param.Get("user_id");
                                    channel_id = param.Get("channel_id");
                                    buffer = Encoding.UTF8.GetBytes(Convert.ToString(OpenAPI.openAPI.addRoleMember(guild_id, role_id, user_id, channel_id)));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "removeRoleMember"://删除身份组成员
                                    guild_id = param.Get("guild_id");
                                    role_id = param.Get("role_id");
                                    user_id = param.Get("user_id");
                                    channel_id = param.Get("channel_id");
                                    buffer = Encoding.UTF8.GetBytes(Convert.ToString(OpenAPI.openAPI.removeRoleMember(guild_id, role_id, user_id, channel_id)));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "get_userChannelPermissions"://获取子频道成员权限
                                    channel_id = param.Get("channel_id");
                                    user_id = param.Get("user_id");
                                    buffer = Encoding.UTF8.GetBytes(OpenAPI.openAPI.get_userChannelPermissions(channel_id, user_id));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "set_userChannelPermissions"://设置成员子频道权限
                                    channel_id = param.Get("channel_id");
                                    user_id = param.Get("user_id");
                                    string add = param.Get("add");
                                    string remove = param.Get("remove");
                                    buffer = Encoding.UTF8.GetBytes(Convert.ToString(OpenAPI.openAPI.set_userChannelPermissions(channel_id, user_id, add, remove)));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "get_ChannelRolePermissions"://获取子频道身份组权限
                                    channel_id = param.Get("channel_id");
                                    role_id = param.Get("role_id");
                                    buffer = Encoding.UTF8.GetBytes(OpenAPI.openAPI.get_ChannelRolePermissions(channel_id, role_id));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "set_ChannelRolePermissions"://修改子频道身份组权限
                                    channel_id = param.Get("channel_id");
                                    role_id = param.Get("role_id");
                                    add = param.Get("add");
                                    remove = param.Get("remove");
                                    buffer = Encoding.UTF8.GetBytes(Convert.ToString(OpenAPI.openAPI.set_ChannelRolePermissions(channel_id, role_id, add, remove)));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "getMessageByMsg_Id"://获取指定消息
                                    channel_id = param.Get("channel_id");
                                    msg_id = param.Get("msg_id");
                                    buffer = Encoding.UTF8.GetBytes(OpenAPI.openAPI.getMessageByMsg_Id(channel_id, msg_id));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "RollBack_Message"://撤回指定消息
                                    channel_id = param.Get("channel_id");
                                    msg_id = param.Get("msg_id");
                                    byte hide = Convert.ToByte(param.Get("hide"));
                                    buffer = Encoding.UTF8.GetBytes(Convert.ToString(OpenAPI.openAPI.RollBack_Message(channel_id, msg_id, hide)));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "createPrivateMessage"://创建私信会话
                                    user_id = param.Get("user_id");
                                    guild_id = param.Get("guild_id");
                                    buffer = Encoding.UTF8.GetBytes(OpenAPI.openAPI.createPrivateMessage(user_id, guild_id));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "send_PrivateMessage"://发送私信消息
                                    guild_id = param.Get("guild_id");
                                    msg = param.Get("msg");
                                    embedMsg = param.Get("embed");
                                    arkMsg = param.Get("ark");
                                    referenceMsg = param.Get("reference");
                                    image = param.Get("image");
                                    msg_id = param.Get("msg_id");
                                    event_id = param.Get("event_id");
                                    markdownMsg = param.Get("markdown");
                                    buffer = Encoding.UTF8.GetBytes(OpenAPI.openAPI.send_PrivateMessage(guild_id, msg, embedMsg, arkMsg, referenceMsg, image, msg_id, markdownMsg));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "RollBack_PrivateMessage"://撤回机器人发送的私信消息
                                    guild_id = param.Get("guild_id");
                                    msg_id = param.Get("msg_id");
                                    hide = Convert.ToByte(param.Get("hide"));
                                    buffer = Encoding.UTF8.GetBytes(Convert.ToString((OpenAPI.openAPI.RollBack_PrivateMessage(guild_id, msg_id, hide))));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "No_Speak"://全体禁言
                                    guild_id = param.Get("guild_id");
                                    string mute_end_timestamp = param.Get("mute_end_timestamp");
                                    string mute_seconds = param.Get("mute_seconds");
                                    buffer = Encoding.UTF8.GetBytes(Convert.ToString(OpenAPI.openAPI.No_Speak(guild_id, mute_end_timestamp, mute_seconds)));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "No_SpeakByUser"://禁言指定成员
                                    guild_id = param.Get("guild_id");
                                    mute_end_timestamp = param.Get("mute_end_timestamp");
                                    mute_seconds = param.Get("mute_seconds");
                                    user_id = param.Get("user_id");
                                    buffer = Encoding.UTF8.GetBytes(Convert.ToString(OpenAPI.openAPI.No_SpeakByUser(guild_id, user_id, mute_end_timestamp, mute_seconds)));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "create_Notice"://创建频道公告
                                    guild_id = param.Get("guild_id");
                                    channel_id = param.Get("channel_id");
                                    msg_id = param.Get("msg_id");
                                    string announces_type = param.Get("type");
                                    string recommend_channels = param.Get("recommend_channels");
                                    buffer = Encoding.UTF8.GetBytes(OpenAPI.openAPI.create_Notice(guild_id, msg_id, channel_id, announces_type, recommend_channels));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "delete_Notice"://删除频道公告
                                    guild_id = param.Get("guild_id");
                                    msg_id = param.Get("msg_id");
                                    buffer = Encoding.UTF8.GetBytes(Convert.ToString(OpenAPI.openAPI.delete_Notice(guild_id, msg_id)));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "addPinsMessage"://设置精华消息
                                    channel_id = param.Get("channel_id");
                                    msg_id = param.Get("msg_id");
                                    buffer = Encoding.UTF8.GetBytes(OpenAPI.openAPI.addPinsMessage(channel_id, msg_id));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "deletePinsMessage"://获取消精华消息
                                    channel_id = param.Get("channel_id");
                                    msg_id = param.Get("msg_id");
                                    buffer = Encoding.UTF8.GetBytes(Convert.ToString(OpenAPI.openAPI.deletePinsMessage(channel_id, msg_id)));
                                    httpSendMessage(outStream, buffer);
                                    break;

                                case "getPinsMessage"://获取子频道下的所有精华消息
                                    channel_id = param.Get("channel_id");
                                    buffer = Encoding.UTF8.GetBytes(OpenAPI.openAPI.getPinsMessage(channel_id));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "getSchedulesList"://获取日程列表
                                    channel_id = param.Get("channel_id");
                                    string since = param.Get("since");
                                    buffer = Encoding.UTF8.GetBytes(OpenAPI.openAPI.getSchedulesList(channel_id, since));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "getScheduleInfo"://获取日程详情
                                    channel_id = param.Get("channel_id");
                                    string schedule_id = param.Get("schedule_id");
                                    buffer = Encoding.UTF8.GetBytes(OpenAPI.openAPI.getScheduleInfo(channel_id, schedule_id));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "create_Schedule"://创建日程
                                    channel_id = param.Get("channel_id");
                                    name = param.Get("name");
                                    string description = param.Get("description");
                                    string start_timestamp = param.Get("start_timestamp");
                                    string end_timestamp = param.Get("end_timestamp");
                                    string jump_channel_id = param.Get("jump_channel_id");
                                    string remind_type = param.Get("remind_type");
                                    buffer = Encoding.UTF8.GetBytes(OpenAPI.openAPI.create_Schedule(channel_id, name, description, start_timestamp, end_timestamp, jump_channel_id, remind_type));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "edit_Schedule"://修改日程信息
                                    channel_id = param.Get("channel_id");
                                    name = param.Get("name");
                                    description = param.Get("description");
                                    start_timestamp = param.Get("start_timestamp");
                                    end_timestamp = param.Get("end_timestamp");
                                    jump_channel_id = param.Get("jump_channel_id");
                                    remind_type = param.Get("remind_type");
                                    schedule_id = param.Get("schedule_id");
                                    buffer = Encoding.UTF8.GetBytes(OpenAPI.openAPI.edit_Schedule(channel_id, schedule_id, name, description, start_timestamp, end_timestamp, jump_channel_id, remind_type));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "delete_Schedule"://删除日程
                                    channel_id = param.Get("channel_id");
                                    schedule_id = param.Get("schedule_id");
                                    buffer = Encoding.UTF8.GetBytes(Convert.ToString(OpenAPI.openAPI.delete_Schedule(channel_id, schedule_id)));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "sendEmoji"://表情表态
                                    channel_id = param.Get("channel_id");
                                    msg_id = param.Get("msg_id");
                                    type = param.Get("type");
                                    string emoji_id = param.Get("emoji_id");
                                    buffer = Encoding.UTF8.GetBytes(Convert.ToString(OpenAPI.openAPI.sendEmoji(channel_id, msg_id, type, emoji_id)));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "deleteEmoji"://删除表情表态
                                    channel_id = param.Get("channel_id");
                                    msg_id = param.Get("msg_id");
                                    type = param.Get("type");
                                    emoji_id = param.Get("emoji_id");
                                    buffer = Encoding.UTF8.GetBytes(Convert.ToString(OpenAPI.openAPI.deleteEmoji(channel_id, msg_id, type, emoji_id)));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "removeGuildMember"://移除频道成员
                                    guild_id = param.Get("guild_id");
                                    user_id = param.Get("user_id");
                                    byte add_blacklist = Convert.ToByte(param.Get("add_blacklist"));
                                    var delete_history_msg_days = param.Get("delete_history_msg_days");
                                    buffer = Encoding.UTF8.GetBytes(Convert.ToString(OpenAPI.openAPI.removeGuildMember(guild_id,user_id,add_blacklist,delete_history_msg_days)));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "getMemberList"://获取频道成员列表
                                    guild_id = param.Get("guild_id");
                                    after = param.Get("after");
                                    limit = param.Get("limit");
                                    buffer = Encoding.UTF8.GetBytes(Convert.ToString(OpenAPI.openAPI.getMemberList(guild_id, after, limit)));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "getMemberListByRole"://获取身份组成员列表
                                    guild_id = param.Get("guild_id");
                                    role_id = param.Get("role_id");
                                    var start_index = param.Get("start_index");
                                    limit = param.Get("limit");
                                    buffer = Encoding.UTF8.GetBytes(Convert.ToString(OpenAPI.openAPI.getMemberListByRole(guild_id,role_id,start_index,limit)));
                                    httpSendMessage(outStream, buffer);
                                    break;
                                case "getMemberInfo"://获取频道成员详情
                                    guild_id = param.Get("guild_id");
                                    user_id = param.Get("user_id");
                                    buffer = Encoding.UTF8.GetBytes(Convert.ToString(OpenAPI.openAPI.getMemberInfo(guild_id,user_id)));
                                    httpSendMessage(outStream, buffer);
                                    break;
                               
                                default://请求函数不存在
                                    outStream.Write(Encoding.UTF8.GetBytes("函数不存在！"), 0, Encoding.UTF8.GetBytes("函数不存在！").Length);
                                    outStream.Close();
                                    break;
                            }
                        }
                        else
                        {
                            outStream.Write(Encoding.UTF8.GetBytes("token验证错误！"), 0, Encoding.UTF8.GetBytes("token验证错误！").Length);
                            outStream.Close();
                        }
                    }
                }
            });
        }
        public static void httpSendMessage(Stream outStream, byte[] buffer)
        {
            outStream.WriteAsync(buffer, 0, buffer.Length);
            outStream.Close();
        }
    }
}
